package com.tqz.jvm;

import java.io.FileInputStream;
import java.lang.reflect.Method;

/**
 * <p>自定义类加载器
 *
 * @author tianqingzhao
 * @since 2022/4/18 19:55
 */
public class MyClassLoaderTest {
    
    public static void main(String[] args) throws Exception {
        // 创建 `d:/myclassloader` 路径，同样在该路径下创建 `com/tqz/jvm` 文件夹，
        // 把生成的 `AppConfig.class` 文件放进去。
        // 如果该路径下所在的包有该class文件，就是用自定义的类加载器加载，
        // 如果没有就是用AppClassLoader向上去加载，知道能加载到为止。
        MyClassLoader myClassLoader = new MyClassLoader("d:/myclassloader");
        Class<?> clazz = myClassLoader.loadClass("com.tqz.jvm.AppConfig");
        Object obj = clazz.newInstance();
        // 调用 `AppConfig` 的init方法
        Method method = clazz.getDeclaredMethod("init", null);
        method.invoke(obj, null);
        // com/tqz/jvm里面不放AppConfig.class文件会是用AppClassLoader类加载器加载，
        // 一旦放了该文件，同时删除该项目target/classes文件夹下面的AppConfig.class文件，就会使用我们自定义的类加载器加载。
        System.out.println(clazz.getClassLoader().getClass().getName());
    }
    
    static class MyClassLoader extends ClassLoader {
        
        private String classPath;
        
        public MyClassLoader(String classPath) {
            this.classPath = classPath;
        }
        
        @Override
        public Class<?> findClass(String name) throws ClassNotFoundException {
            try {
                byte[] data = loadByte(name);
                return defineClass(name, data, 0, data.length);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ClassNotFoundException("类 " + name + " 找不到");
            }
        }
        
        private byte[] loadByte(String name) throws Exception {
            name = name.replaceAll("\\.", "/");
            FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
            int len = fis.available();
            byte[] data = new byte[len];
            fis.read(data);
            fis.close();
            return data;
        }
        
        @Override
        protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
            synchronized (getClassLoadingLock(name)) {
                // First, check if the class has already been loaded
                Class<?> c = findLoadedClass(name);
                
                if (c == null) {
                    // If still not found, then invoke findClass in order
                    // to find the class.
                    long t1 = System.nanoTime();
                    
                    // 使我们自己的类就使用自定义类加载器加载，否则就使用双亲委派机制加载
                    if (name.startsWith("com.tqz.jvm.AppConfig")) {
                        c = findClass(name);
                    } else {
                        c = getParent().loadClass(name);
                    }
                    
                    // this is the defining class loader; record the stats
                    sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1);
                    sun.misc.PerfCounter.getFindClasses().increment();
                }
                if (resolve) {
                    resolveClass(c);
                }
                return c;
            }
        }
    }
}
